package com.student_system.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.student_system.system.entity.SysUserRole;
import com.student_system.system.mapper.SysUserRoleMapper;
import com.student_system.system.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljy
 * @since 2025-05-14
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {
    @Transactional
    @Override
    public List<Integer> getRoleIdByUserId(Integer userId) {
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<SysUserRole> userRoles = this.list(wrapper);
        List<Integer> roleIds = new ArrayList<>();
        for (SysUserRole userRole : userRoles){
            roleIds.add(userRole.getRoleId());
        }
        return roleIds;
    }

    @Override
    public void saveUserRoles(Integer userId, List<Integer> roleIds) {
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        //删除原有关联
        this.remove(wrapper);
        //循环保存所有数据
        List<SysUserRole> list = new ArrayList<>();
        for (Integer roleId : roleIds) {
            SysUserRole sur = new SysUserRole();
            sur.setUserId(userId);
            sur.setRoleId(roleId);
            list.add(sur);
        }
        this.saveBatch(list);
    }
}
